package com.smartlight.godlight;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.smartlight.godlight.adapter.BlessingAdapter;
import com.smartlight.godlight.adapter.GridImageAdapter;
import com.smartlight.godlight.constant.GodlApi;
import com.smartlight.godlight.listener.OnItemClickListener;
import com.smartlight.godlight.model.AppInfo;
import com.smartlight.godlight.model.Blessinng;
import com.smartlight.godlight.model.Buddha;
import com.smartlight.godlight.utils.OkHttpUtils;
import com.smartlight.godlight.utils.SharedPreferencesUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class SelectSentence extends AppCompatActivity {

    private final String TAG = "SelectGod";
    private List<Blessinng> blessinngList = new ArrayList<Blessinng>();
    private RecyclerView recyclerView;
    private AppInfo appInfo;
    private SwipeRefreshLayout swipeRefreshLayout;
    private  BlessingAdapter adapter;

    @Override
    protected void  onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.selectsentence);

        // actionbar
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        // 获取ActionBar对象（实际上是Toolbar）并设置属性
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true); // 显示返回箭头
            actionBar.setHomeAsUpIndicator(R.drawable.arrow_yellow); // 设置返回图标
            actionBar.setTitle("请选择未被点亮的佛灯"); // 设置标题文字
//            toolbar.setTitleTextColor(ContextCompat.getColor(this, R.color.dark_yellow));
        }

        // 加载数据
        initData();





//        Button btn_sentencesubmit = findViewById(R.id.btn_sentencesubmit);
//        btn_sentencesubmit.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                Intent intent = new Intent();
//                intent.setClass(SelectSentence.this,WorshipData.class);
//                startActivity(intent);
////                Toast.makeText(SelectSentence.this, "祈福语选择完成", Toast.LENGTH_SHORT).show();
//            }
//        });
    }

    private void loadMoreData() {
        initData();
        adapter.notifyDataSetChanged(); // 通知适配器数据已改变，UI将更新显示新数据
        adapter.setFooterViewVisible(true);
    }

    private void loadData() {
        adapter.notifyDataSetChanged(); // 通知适配器数据已改变，UI将更新显示新数据
        swipeRefreshLayout.setRefreshing(false); // 停止刷新动画
        adapter.setFooterViewVisible(true);
    }

    private void initData() {

        if (SharedPreferencesUtils.getParam(this,"appInfo", "") != ""){
            Object appInfoStr = SharedPreferencesUtils.getParam(this, "appInfo", "");
            JsonObject jsonObject = new Gson().fromJson((String) appInfoStr, JsonObject.class);
            Log.d(TAG, "-存在---读取数据---" + jsonObject.get("data").toString());
            appInfo = new Gson().fromJson(jsonObject.get("data").toString(), AppInfo.class);
            Log.d(TAG, "-存在---读取数据---" + appInfo.getTitle() + " :"  + appInfo.getBackgroundUrl());
            Log.d(TAG, "-存在---读取佛像数据---" + appInfo.getBuddhaList().size());
            // 刷新UI
            setBlessing();
        }
        else {
            OkHttpUtils.get(GodlApi.GET_APP_INFO, new Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    GodlApi.printLog(TAG, "接口:" + GodlApi.GET_APP_INFO + ", 请求失败, " + e.toString());
                }

                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                    String data = response.body().string();
                    GodlApi.printLog(TAG, "接口:" + GodlApi.GET_APP_INFO + ", 请求成功, 返回数据：" + data);
                    Object appInfoStr = SharedPreferencesUtils.getParam(SelectSentence.this, "appInfo", "");
                    JsonObject jsonObject = new Gson().fromJson(data, JsonObject.class);
                    Log.d(TAG, "----接口请求数据---" + jsonObject.get("data").toString());
                    appInfo = new Gson().fromJson(jsonObject.get("data").toString(), AppInfo.class);
                    // 刷新UI
                    setBlessing();
                }
            });
        }
    }

    private void setBlessing() {
        blessinngList = appInfo.getBlessingList();

        recyclerView = findViewById(R.id.recyclerView);
        swipeRefreshLayout = findViewById(R.id.swipeRefreshLayout);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager (this);
        recyclerView.setLayoutManager(linearLayoutManager); // 设置网格布局管理器。
        adapter = new BlessingAdapter(this, blessinngList, 10); // 初始化适配器。
        recyclerView.setAdapter(adapter); // 设置适配器。
        swipeRefreshLayout.setOnRefreshListener(() -> {
            // 设置下拉刷新监听器。这里可以调用加载数据的逻辑。例如：
            Log.d(TAG, "下拉刷新更多。。。。。");
            Toast.makeText(this, "下拉刷新更多", Toast.LENGTH_LONG).show();
            loadData();
        });


        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                Intent intent2 = new Intent();
                Blessinng blessinng = blessinngList.get(position);
                intent2.putExtra("blessing", blessinng.getContent());
                setResult(RESULT_OK, intent2);
                finish();
            }
        });

        // 监听上拉刷新
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                int lastVisibleItem = layoutManager.findLastCompletelyVisibleItemPosition();
                int totalItemCount = layoutManager.getItemCount();
                if (lastVisibleItem >= totalItemCount - 1 && dy > 0) {
                    Toast.makeText(SelectSentence.this, "滑动到底部", Toast.LENGTH_LONG).show();
                    // 判断是否滚动到底部，并且是向上滚动（dy > 0）触发的滚动事件，避免误判为下拉刷新时的滚动到底部事件
                    loadMoreData(); // 执行加载更多数据的操作
                }
            }
        });
    }

}
